#include "render/Mesh.h"

static void setupMesh(Mesh& m, const float* verts, size_t vcount, const unsigned int* idx, size_t icount){
    glGenVertexArrays(1,&m.vao);
    glGenBuffers(1,&m.vbo);
    glGenBuffers(1,&m.ebo);
    glBindVertexArray(m.vao);
    glBindBuffer(GL_ARRAY_BUFFER,m.vbo);
    glBufferData(GL_ARRAY_BUFFER,vcount*sizeof(float),verts,GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,m.ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,icount*sizeof(unsigned int),idx,GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,6*sizeof(float),(void*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,6*sizeof(float),(void*)(3*sizeof(float)));
    m.indexCount = (GLsizei)icount;
    glBindVertexArray(0);
}

Mesh Mesh::Cube(){
    float v[] = {
        -0.5f,-0.5f,-0.5f, 0,0,-1,
         0.5f,-0.5f,-0.5f, 0,0,-1,
         0.5f, 0.5f,-0.5f, 0,0,-1,
        -0.5f, 0.5f,-0.5f, 0,0,-1,

        -0.5f,-0.5f, 0.5f, 0,0,1,
         0.5f,-0.5f, 0.5f, 0,0,1,
         0.5f, 0.5f, 0.5f, 0,0,1,
        -0.5f, 0.5f, 0.5f, 0,0,1,

        -0.5f, 0.5f, 0.5f, -1,0,0,
        -0.5f, 0.5f,-0.5f, -1,0,0,
        -0.5f,-0.5f,-0.5f, -1,0,0,
        -0.5f,-0.5f, 0.5f, -1,0,0,

         0.5f, 0.5f, 0.5f, 1,0,0,
         0.5f, 0.5f,-0.5f, 1,0,0,
         0.5f,-0.5f,-0.5f, 1,0,0,
         0.5f,-0.5f, 0.5f, 1,0,0,

        -0.5f,-0.5f,-0.5f, 0,-1,0,
         0.5f,-0.5f,-0.5f, 0,-1,0,
         0.5f,-0.5f, 0.5f, 0,-1,0,
        -0.5f,-0.5f, 0.5f, 0,-1,0,

        -0.5f, 0.5f,-0.5f, 0,1,0,
         0.5f, 0.5f,-0.5f, 0,1,0,
         0.5f, 0.5f, 0.5f, 0,1,0,
        -0.5f, 0.5f, 0.5f, 0,1,0,
    };
    unsigned int i[] = {
        0,1,2, 2,3,0,
        4,5,6, 6,7,4,
        8,9,10, 10,11,8,
        12,13,14, 14,15,12,
        16,17,18, 18,19,16,
        20,21,22, 22,23,20
    };
    Mesh m; setupMesh(m,v,sizeof(v)/sizeof(float),i,sizeof(i)/sizeof(unsigned int)); return m;
}

Mesh Mesh::Plane(){
    float v[] = {
        -0.5f,0.0f,-0.5f, 0,1,0,
         0.5f,0.0f,-0.5f, 0,1,0,
         0.5f,0.0f, 0.5f, 0,1,0,
        -0.5f,0.0f, 0.5f, 0,1,0,
    };
    unsigned int i[] = {0,1,2, 2,3,0};
    Mesh m; setupMesh(m,v,sizeof(v)/sizeof(float),i,sizeof(i)/sizeof(unsigned int)); return m;
}